
var Resource = require("../models/resource");
var db = require("../models/mysql");
var moment = require('moment');
let downloadLinks='http://localhost:3000/download';
//添加资源
exports.addResource = function(name,brief,links,callback){
    var newRecord = {};
    newRecord.name = name;
    newRecord.links = links;
    newRecord.pubtime = moment().format('YYYY-MM-DD HH:mm:ss');
    newRecord.brief = brief;
    Resource.create(newRecord, function(err, results) {
        let id=results.id;
        Resource.find({id:id},function(err,resource){
            resource[0].name = name;
            resource[0].links = downloadLinks+"/"+id;
            resource[0].brief = brief;
            resource[0].save(function(err,result){
                return callback(err,result);
            });
        });

    });
};
//资源列表
exports.resouceList = function(pageSize,pageNow,callback){

    //计算偏移量
    var offset = pageSize * (pageNow - 1);

    Resource.find().limit(pageSize).offset(offset).order('-pubtime').all(function(err,resources){

        return callback(err,resources);
    });
};
//资源列表
exports.resourceSearchList = function(param,callback){

    var pageSize = param.pageSize;
    var pageNow = param.pageNow;
    var key = param.key;
    //计算偏移量
    var offset = pageSize * (pageNow - 1);
    var sql = "SELECT t1.* FROM resource as t1  WHERE 1=1 ";
    if(key)
    {
        sql +=" AND t1.brief like '%"+key+"%'";
    }
    sql +=" order by t1.pubtime desc";
    sql += " LIMIT "+offset+","+pageSize+"";
    db.driver.execQuery(sql,function(err,resources){

        console.log(err);
        return callback(err,resources);
    });
};
//资源总记录数
exports.resourceCount = function(callback){
    Resource.count(function(err,count){
        return callback(err,count);
    });
};
//删除资源
exports.deleteById = function(callback){
    Resource.deleteById(function(err){
        return callback(err);
    });
};
//根据id查询资源
exports.resourceById = function(id,callback){

    Resource.find({id:id},function(err,resource){

        return callback(err,resource);
    });
};
//更新资源
exports.resourceUpdate = function(id,name,brief,links,callback){

    Resource.find({id:id},function(err,resource){

        resource[0].name = name;
        resource[0].links = links;
        resource[0].brief = brief;
        resource[0].save(function(err,result){
            return callback(err,result);
        });
    });
};
//最新资源  按时间排序  5篇资源
exports.resourceNew = function(callback){

    Resource.find().limit(5).order('-pubtime').all(function(err,resources){
            return callback(err,resources);
    });
};
//更新资源的下载数
exports.resourceDownNumUpdate = function(id,callback){

    Resource.find({id:id},function(err,resource){

        resource[0].downnum = parseInt(resource[0].downnum +1);
        resource[0].save(function(err,result){

            return callback(err,result);
        });
    });
};


